import { loginActionAPI } from '@/api/login'
import { getUserInfoAPI } from '@/api/user'

const userModule = {
  namespaced: true,
  state: () => {
    return {
      token: '',
      // 用户信息对象
      userInfo: {}
    }
  },
  mutations: {
    setToken: (state, token) => {
      state.token = token
    },
    removeToken: (state) => {
      state.token = ''
    },
    setUserInfo: (state, res) => {
      state.userInfo = res
    }
  },
  actions: {
    // 用户登录
    loginAction: async ({ commit }, userForm) => {
      const resp = await loginActionAPI(userForm)

      // 提交mutations,完成对state中的
      commit('setToken', resp.data.token)
    },
    // 退出登录：action（包装多个mutation）
    logoutAction: ({ commit }) => {
      commit('removeToken')
    },
    // 获取用户基本信息
    getUserInfoAction: async ({ commit }) => {
      const { data: res } = await getUserInfoAPI()

      if (res.code === 0) {
        // 调用 mutation 函数更新用户的基本信息
        commit('setUserInfo', res.data)
        return
      }
      // 提交mutations
      commit('setUserInfo', res)
    }
  }
}

export default userModule
